package com.wx.servlet;

import com.wx.entity.ImgAndTxtMsg;
import com.wx.entity.ImgMsg;
import com.wx.entity.TextMsg;
import com.wx.util.XmlUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;

public class WeChatServlet
  extends HttpServlet
{
  private static final String URL = "http://localhost/Maven3/gpa/getparams";
  
  public void destroy()
  {
    super.destroy();
  }
  
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    System.out.println("收到微信验证请求");
    
    String signature = request.getParameter("signature");
    
    String timestamp = request.getParameter("timestamp");
    
    String nonce = request.getParameter("nonce");
    
    String echostr = request.getParameter("echostr");
    System.out.println("signature=" + signature);
    System.out.println("timestamp=" + timestamp);
    System.out.println("nonce=" + nonce);
    System.out.println("echostr=" + echostr);
    PrintWriter out = null;
    try
    {
      out = response.getWriter();
      

      out.print(echostr);
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    finally
    {
      out.close();
      out = null;
    }
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    String result = "success";
    try
    {
      Map<String, String> map = XmlUtil.parseXml(request);
      
      System.out.println("******************");
      try
      {
        for (String key : map.keySet()) {
          System.out.println("Key = " + key + "---value = " + 
            (String)map.get(key));
        }
        System.out.println("******************");
        String msgType = (String)map.get("MsgType");
        String fromUserName = (String)map.get("FromUserName");
        String toUserName = (String)map.get("ToUserName");
        

        if (msgType.equals("event"))
        {
          String event = (String)map.get("Event");
          if(event.equals("subscribe")){
          	//KoKhVyCcyu5Gj4cAIVMZoFywjWKRV6Xp_NKb0l1iIYA
          	 ImgAndTxtMsg tmMsg = new ImgAndTxtMsg();
               tmMsg.setFromUserName(fromUserName);
               tmMsg.setToUserName(toUserName);
               tmMsg.setTitle("羿戓信息");
               tmMsg.setDescription("有羿戓！\n有你的善念！\n有你的爱好和特长！\n天下便在无难事。");
             	 tmMsg.setUrl("http://mp.weixin.qq.com/s?__biz=MzA3NTc4MjcyOQ==&mid=504711312&idx=1&sn=7e6d728d7c333b5b7c9a7ecc7a0dc379&chksm=048aa7b633fd2ea0b37df6be4c0590bba01ddadfee13e63045dbccba6e960304b07e426a7dc6#rd");
             	 tmMsg.setPicUrl("http://mmbiz.qpic.cn/mmbiz_jpg/YrnxsmB0HFBU4ib73tv6JibP48K9u6nQtOpOicUNgt1EZC3JZfM9z4y34AdhBfxct3OhdaQkISIEQSB79acBLwib8g/0?wx_fmt=jpeg");
             	 result = tmMsg.getXml();
          }else if (event.equals("CLICK"))
          {
            String key = (String)map.get("EventKey");
            if (key.equals("Collection_of_documents"))
            {
              TextMsg tmMsg = new TextMsg();
              tmMsg.setFromUserName(fromUserName);
              tmMsg.setToUserName(toUserName);
              tmMsg.setContent("投稿信箱：epaper@eaoogle.com \n联系电话：18918134319\n主题：创新理论、模式、技术新闻\n注意：优先采纳原创，稿酬(120-300)元/千字，投稿时请提供联系方式及收款账户");
              result = tmMsg.getXml();
            }
          }
          else if (!event.equals("location_select"))
          {
            if (!event.equals("VIEW")) {
              if (event.equals("scancode_waitmsg"))
              {
                String ScanResult = (String)map.get("ScanResult");
                TextMsg tmMsg = new TextMsg();
                tmMsg.setFromUserName(fromUserName);
                tmMsg.setToUserName(toUserName);
                tmMsg.setContent("扫描结果：" + ScanResult);
                result = tmMsg.getXml();
              }
              else if (event.equals("SCAN"))
              {
                System.out.println(fromUserName + "扫描了二维码");
                JSONObject jsobj1 = new JSONObject();
                jsobj1 = JSONObject.fromObject("{'name':'" + (String)map.get("FromUserName") + "','deviceName':'" + ((String)map.get("EventKey")).replace("qrscene_", "") + "'}");
                System.out.println("{'name':'" + (String)map.get("FromUserName") + "','devicename':'" + (String)map.get("EventKey") + "'}");
                //post(jsobj1);
              }
            }
          }
        }
        else if (msgType.equals("text"))
        {
          String content = (String)map.get("Content");
          System.out.println(fromUserName + "给后台发送了消息：" + content);
          ImgMsg tmMsg = new ImgMsg();
          tmMsg.setFromUserName(fromUserName);
          tmMsg.setToUserName(toUserName);
          if("修改菜单".equals(content)){
         // tmMsg.setContent("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx10b3d172343b72ee&redirect_uri=http%3a%2f%2fabc.aiyouei.com/Maven3/eaoogle/wx.jsp&response_type=code&scope=snsapi_userinfo&state=STATE");
         // String str = "<xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[fromUser] ]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[你好] ]></Content> </xml>";
          //System.out.println("xml:" + tmMsg.getXml());
        	  tmMsg.setMediaId("KoKhVyCcyu5Gj4cAIVMZoHPP-FNxO0htv43I4vhdSyo");
        	  result = tmMsg.getXml();
          }
        }
        else if (msgType.equals("location"))
        {
          System.out.println(fromUserName + "给后台发送了位置消息");
          String Location_X = (String)map.get("Location_X");
          String Location_Y = (String)map.get("Location_Y");
          String Label = (String)map.get("Label");
          TextMsg tmMsg = new TextMsg();
          tmMsg.setFromUserName(fromUserName);
          tmMsg.setToUserName(toUserName);
          tmMsg.setContent("纬度：" + Location_X + "\n经度：" + Location_Y + 
            "\n位置信息：" + Label);
          result = tmMsg.getXml();
        }
        else if (msgType.equals("image"))
        {
          System.out.println(fromUserName + "给后台发送了图片");
          
          String mediaId = (String)map.get("MediaId");
          
          ImgMsg msg = new ImgMsg(toUserName, fromUserName, mediaId);
          result = msg.getXml();
        }
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
      System.out.println(result);
      out.print(result);
      out.flush();
      out.close();
    }
    catch (Exception e)
    {
      System.out.println("___________________________________________________________~~~~~~~~~~~~~~~~~~~~~");
    }
  }
  
  public void init()
    throws ServletException
  {}
  
  public String post(JSONObject json)
  {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost/Maven3/gpa/getparams");
    
    post.setHeader("Content-Type", "application/json");
    post.addHeader("Authorization", "Basic YWRtaW46");
    String result = "";
    try
    {
      StringEntity s = new StringEntity(json.toString(), "utf-8");
      s.setContentEncoding(new BasicHeader("Content-Type", 
        "application/json"));
      post.setEntity(s);
      

      HttpResponse httpResponse = client.execute(post);
      

      InputStream inStream = httpResponse.getEntity().getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        inStream, "utf-8"));
      StringBuilder strber = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        strber.append(line + "\n");
      }
      inStream.close();
      
      result = strber.toString();
      System.out.println(result);
      if (httpResponse.getStatusLine().getStatusCode() == 200) {
        System.out.println("请求服务器成功，做相应处理");
      } else {
        System.out.println("请求服务端失败");
      }
    }
    catch (Exception e)
    {
      System.out.println("请求异常");
      throw new RuntimeException(e);
    }
    return result;
  }
	/**
	 * 绑定成功推送消息
	 * 
	 * @param touser
	 */
}
